package com.example.baseutils.activity

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.example.baseutils.*
import com.permissionx.guolindev.PermissionX
import java.lang.ref.WeakReference
import java.lang.reflect.Method
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.system.exitProcess


/**
 * Author by lp,on 2021/6/30/030,10:52.
 */
abstract class BaseActivity : AppCompatActivity() {
    companion object {
        //增加activity管理，便于异常时候直接退出应用
        val activityList = CopyOnWriteArrayList<WeakReference<Activity>>()
    }

    protected val weakReference: WeakReference<Activity> by lazy { WeakReference(this) }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i("BaseActivity", "onCreate: ")
//        Desity.setAppDesity(BaseApplication.instance, this)
//        Desity.reset(this)
        activityList.add(weakReference)
        /**
         * 保证界面常亮
         */
        window.setFlags(
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
            WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
        )
        //强制竖屏
//        requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        if (AppUtils.isNanopi(null)) {
            //设置为桌面
            if (!AppUtils.isDefaultHome(this)) {
                AppUtils.setDefaultLauncher(this, javaClass.name)
            }
        }
    }

    private fun hideNavigationBar() {
        /**
         * 隐藏标题栏 状态栏通过主题隐藏
         */
        supportActionBar?.hide()
        if (Build.VERSION.SDK_INT in 12..18) {
            val v = this.window.decorView
            v.systemUiVisibility = View.GONE
        } else {
            val window = window
            val params = window.attributes
            params.systemUiVisibility = (View.SYSTEM_UI_FLAG_HIDE_NAVIGATION //隐藏虚拟按键
                    or View.SYSTEM_UI_FLAG_IMMERSIVE
                    or View.SYSTEM_UI_FLAG_FULLSCREEN) //全屏
            window.attributes = params
        }
        //顶部状态栏
        disableStatusBar()
    }

    protected open fun gotPermision() {
        LogUtils.log("BaseActivity", "gotPermision")
    }

    protected fun requestPermision(activity: BaseActivity, vararg permissions: String) {
        PermissionX.init(activity)
            .permissions(
                *permissions
            )
            .onExplainRequestReason { deniedList ->
                showRequestReasonDialog(deniedList, "即将重新申请的权限是程序必须依赖的权限", "我已明白", "取消")
            }
            .onForwardToSettings { deniedList ->
                Log.i("BaseActivity", "requestPermision: $deniedList")
                showForwardToSettingsDialog(deniedList, "您需要去应用程序设置当中手动开启权限", "我已明白", "取消")
            }
            .request { allGranted, grantedList, deniedList ->
                if (allGranted) {
                    activity.gotPermision()
//                    "所有申请的权限都已通过".showToast(this)
                } else {
//                    "您拒绝了如下权限：$deniedList".showToast(this)
                }
            }

    }

    override fun onResume() {
        super.onResume()
        if (AppUtils.isNanopi(null)) {
            hideNavigationBar()
        } else {
//            NavigationBarUtil.hideNavigationBar(window)
            StatusBarUtils.setStatusBarBlackText(this)
            StatusBarUtils.immersive(this)
//            StatusBarUtils.fullScreen(this)
        }
    }

    override fun onWindowFocusChanged(hasFocus: Boolean) {
        super.onWindowFocusChanged(hasFocus)
        Log.e("BaseAciviy", "onWindowFocusChanged")
        if (AppUtils.isNanopi(null)) {
            hideNavigationBar()
        } else {
            Log.e("BaseAciviy", "不是nanopi")
//            NavigationBarUtil.hideNavigationBar(window)
            return
        }

    }

    private var isBackExit = false
    protected fun exitState(state: Boolean) {
        isBackExit = state
    }

    private var currentTime = System.currentTimeMillis()
    override fun onBackPressed() {
        if (!isBackExit) {
            super.onBackPressed()
            return
        }
        if (System.currentTimeMillis() - currentTime > 2 * 1000) {
            "再次 返回退出应用".showToast()
            currentTime = System.currentTimeMillis()
        } else {
            exitProcess(0)
        }
    }

    /***
     * 系统级别应用通过反射关闭状态栏、仅限于nanopi使用
     * */
    @SuppressLint("WrongConstant")
    fun disableStatusBar(disable: Boolean = true) {
        val service = getSystemService("statusbar")
        try {
            val statusBarManager = Class.forName("android.app.StatusBarManager")
            val expand: Method =
                statusBarManager.getMethod("disable", Int::class.javaPrimitiveType)
            val DISABLE_EXPAND = 0x00010000//顶部状态栏4.2以上的整形标识
            val DISABLE_RECENT = 0x01000000//底部最近任务
            val DISABLE_HOME = 0x00200000//底部home
            val DISABLE_EXPAND_LOW = 0x00000001//4.2以下的整形标识
            val DISABLE_NONE = 0x00000000//取消StatusBar所有disable属性，即还原到最最原始状态
            if (disable) {
                expand.invoke(service, DISABLE_EXPAND or DISABLE_RECENT or DISABLE_HOME)
            } else {
                expand.invoke(service, DISABLE_NONE)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {

            // 获得当前得到焦点的View，一般情况下就是EditText（特殊情况就是轨迹求或者实体案件会移动焦点）
            val v = currentFocus
            if (isShouldHideInput(v, ev)) {
                hideSoftInput(v!!.windowToken)
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，来判断是否隐藏键盘，因为当用户点击EditText时没必要隐藏
     *
     * @param v
     * @param event
     * @return
     */
    private fun isShouldHideInput(v: View?, event: MotionEvent): Boolean {
        if (v != null && v is EditText) {
            val l = intArrayOf(0, 0)
            v.getLocationInWindow(l)
            val left = l[0]
            val top = l[1]
            val bottom = top + v.getHeight()
            val right = (left
                    + v.getWidth())
            return !(event.x > left && event.x < right && event.y > top && event.y < bottom)
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditView上，和用户用轨迹球选择其他的焦点
        return false
    }

    /**
     * 多种隐藏软件盘方法的其中一种
     *
     * @param token
     */
    private fun hideSoftInput(token: IBinder?) {
        if (token != null) {
            val im: InputMethodManager =
                getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            im.hideSoftInputFromWindow(
                token,
                InputMethodManager.HIDE_NOT_ALWAYS
            )
        }
    }

    override fun onStop() {
        super.onStop()
        removeAllToast()
    }
    override fun onDestroy() {
        activityList.remove(weakReference)
        super.onDestroy()
    }
//    override fun attachBaseContext(newBase: Context) {
//        super.attachBaseContext(object : ContextWrapper(newBase) {
//            override fun getSystemService(name: String): Any {
//                return if (Context.AUDIO_SERVICE == name) {
//                    "Context.AUDIO_SERVICE".log("BaseActivity")
//                    applicationContext.getSystemService(name) ?: super.getSystemService(name)
//                } else super.getSystemService(name)
//            }
//        })
//    }
}